<template>
  <!-- 课程配分 -->
  <div>
    <onboardingGuide
      @step5Click="step5Click"
      :step="5"
      :show.sync="onboardingGuideShow"
      :rect="onboardingGuideRect"
      :radius="30"
    ></onboardingGuide>
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      title="课程配分"
      :visible="open"
      width="1120px"
      append-to-body
      top="20px"
      @close="cancel()"
    >
      <div>
        <div class="sign">
          <i class="el-icon-info"></i>
          <div>
            注：审批通过后，将对本课程学习状态为【学习中】&【未开始】的学生生效;每项“得分*权重“之和计算学生该课程最终得分（{{
              courseType != 3
                ? '“课后作业““课后考核“'
                : '“课后作业““任务考核““终结性考核“'
            }}需进行二次配分）。
          </div>
        </div>
        <!-- 2.1.2总评 -->
        <div class="containBox">
          <div class="score_detail_title">
            <div>总评</div>
            <div ref="studentScoreEdit">
              <el-button
                size="mini"
                @click="showTotalEdit = true"
                v-show="
                  !showTotalEdit &&
                  ($route.query.type == 'add' || $route.query.type == 'edit')
                "
              >编 辑
              </el-button>
              <el-button
                size="mini"
                v-show="showTotalEdit"
                v-preventReClick
                type="primary"
                @click="checkTotalAll"
              >保 存
              </el-button>
            </div>
          </div>
          <div>
            <!-- 2.1.2非工学一体课程总评（通用课程） courseType==3为工学一体-->
            <el-table
              v-if="courseType != 3"
              :data="distributionList"
              v-loading="loading"
              border
            >
              <el-table-column
                align="center"
                prop="attendanceScorePercentage"
                label="考勤"
              >
                <template #header>
                  <span>
                    考勤
                    <el-tooltip
                      class="item"
                      effect="dark"
                      :content="content"
                      placement="top"
                    >
                      <i style="cursor: pointer" class="el-icon-info"></i>
                      <div slot="content">
                        初始100分，在授课过程中根据考情异常情况扣分（排课时自定义异常情况扣分分数）
                      </div>
                    </el-tooltip>
                  </span>
                </template>
                <template slot-scope="scope">
                  <div
                    v-if="
                      ($route.query.type == 'add' ||
                        $route.query.type == 'edit') &&
                      showTotalEdit
                    "
                  >
                    <el-input
                      v-model="scope.row.attendanceScorePercentage"
                      oninput="value=value.replace(/[^\d.]/,'').replace(/(\.\d\d)\d+$/,'\$1'); if(parseFloat(value) > 100) value='100';"
                      style="width: 72px"
                    ></el-input>
                    %
                  </div>
                  <div v-else>
                    {{
                      scope.row.attendanceScorePercentage
                        ? scope.row.attendanceScorePercentage
                        : '0'
                    }}%
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                prop="disciplineScorePercentage"
                label="纪律"
              >
                <template #header>
                  <span>
                    纪律
                    <el-tooltip
                      class="item"
                      effect="dark"
                      :content="content"
                      placement="top"
                    >
                      <i style="cursor: pointer" class="el-icon-info"></i>
                      <div slot="content">
                        排课时自定义初始分，并在授课过程中进行分数加减（取0～100分计算得分）
                      </div>
                    </el-tooltip>
                  </span>
                </template>
                <template slot-scope="scope">
                  <div
                    v-if="
                      ($route.query.type == 'add' ||
                        $route.query.type == 'edit') &&
                      showTotalEdit
                    "
                  >
                    <el-input
                      v-model="scope.row.disciplineScorePercentage"
                      oninput="value=value.replace(/[^\d.]/,'').replace(/(\.\d\d)\d+$/,'\$1'); if(parseFloat(value) > 100) value='100';"
                      style="width: 72px"
                    ></el-input>
                    %
                  </div>
                  <div v-else>
                    {{
                      scope.row.disciplineScorePercentage
                        ? scope.row.disciplineScorePercentage
                        : '0'
                    }}%
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                prop="usualScorePercentage"
                label="课堂表现"
              >
                <template #header>
                  <span>
                    课堂表现
                    <el-tooltip
                      class="item"
                      effect="dark"
                      :content="content"
                      placement="top"
                    >
                      <i style="cursor: pointer" class="el-icon-info"></i>
                      <div slot="content">
                        排课时自定义初始分，并在授课过程中进行分数加减（取0～100分计算得分）
                      </div>
                    </el-tooltip>
                  </span>
                </template>
                <template slot-scope="scope">
                  <div
                    v-if="
                      ($route.query.type == 'add' ||
                        $route.query.type == 'edit') &&
                      showTotalEdit
                    "
                  >
                    <el-input
                      v-model="scope.row.usualScorePercentage"
                      oninput="value=value.replace(/[^\d.]/,'').replace(/(\.\d\d)\d+$/,'\$1'); if(parseFloat(value) > 100) value='100';"
                      style="width: 72px"
                    ></el-input>
                    %
                  </div>
                  <div v-else>
                    {{
                      scope.row.usualScorePercentage
                        ? scope.row.usualScorePercentage
                        : '0'
                    }}%
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                prop="dailyScoreTotal"
                label="课后作业"
              >
                <template #header>
                  <span>
                    课后作业
                    <el-tooltip
                      class="item"
                      effect="dark"
                      :content="content"
                      placement="top"
                    >
                      <i style="cursor: pointer" class="el-icon-info"></i>
                      <div slot="content">
                        编辑课程时在内容中创建，学生学习该内容时完成，按照【课后作业权重明细】计算得分
                      </div>
                    </el-tooltip>
                  </span>
                </template>
                <template slot-scope="scope">
                  <div
                    v-if="
                      ($route.query.type == 'add' ||
                        $route.query.type == 'edit') &&
                      showTotalEdit
                    "
                  >
                    <el-input
                      v-model="scope.row.homeworkScorePercentage"
                      oninput="value=value.replace(/[^\d.]/,'').replace(/(\.\d\d)\d+$/,'\$1'); if(parseFloat(value) > 100) value='100';"
                      style="width: 72px"
                    ></el-input>
                    %
                  </div>
                  <div v-else>
                    {{
                      scope.row.homeworkScorePercentage
                        ? scope.row.homeworkScorePercentage
                        : '0'
                    }}%
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                prop="processScorePercentage"
                label="课后考核"
              >
                <template #header>
                  <span>
                    课后考核
                    <el-tooltip
                      class="item"
                      effect="dark"
                      :content="content"
                      placement="top"
                    >
                      <i style="cursor: pointer" class="el-icon-info"></i>
                      <div slot="content">
                        编辑课程时在内容中创建，学生学习该内容时进行考核，按照【任务考核权重明细】计算得分
                      </div>
                    </el-tooltip>
                  </span>
                </template>
                <template slot-scope="scope">
                  <div
                    v-if="
                      ($route.query.type == 'add' ||
                        $route.query.type == 'edit') &&
                      showTotalEdit
                    "
                  >
                    <el-input
                      v-model="scope.row.processScorePercentage"
                      oninput="value=value.replace(/[^\d.]/,'').replace(/(\.\d\d)\d+$/,'\$1'); if(parseFloat(value) > 100) value='100';"
                      style="width: 72px"
                    ></el-input>
                    %
                  </div>
                  <div v-else>
                    {{
                      scope.row.processScorePercentage
                        ? scope.row.processScorePercentage
                        : '0'
                    }}%
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                prop="otherScorePercentage"
                label="其他"
              >
                <template #header>
                  <span>
                    其他
                    <el-tooltip
                      class="item"
                      effect="dark"
                      :content="content"
                      placement="top"
                    >
                      <i style="cursor: pointer" class="el-icon-info"></i>
                      <div slot="content">
                        排课时自定义初始分，并在授课过程中进行分数加减（取0～100分计算得分）
                      </div>
                    </el-tooltip>
                  </span>
                </template>
                <template slot-scope="scope">
                  <div
                    v-if="
                      ($route.query.type == 'add' ||
                        $route.query.type == 'edit') &&
                      showTotalEdit
                    "
                  >
                    <el-input
                      v-model="scope.row.otherScorePercentage"
                      oninput="value=value.replace(/[^\d.]/,'').replace(/(\.\d\d)\d+$/,'\$1'); if(parseFloat(value) > 100) value='100';"
                      style="width: 72px"
                    ></el-input>
                    %
                  </div>
                  <div v-else>
                    {{
                      scope.row.otherScorePercentage
                        ? scope.row.otherScorePercentage
                        : '0'
                    }}%
                  </div>
                </template>
              </el-table-column>
            </el-table>
            <!-- 2.1.2工学一体课程总评 -->
            <el-table
              v-if="courseType == 3"
              :data="distributionList"
              v-loading="loading"
              border
            >
              <el-table-column label="过程性考核" align="center">
                <el-table-column
                  align="center"
                  prop="usualScorePercentage"
                  label="课堂表现"
                >
                  <template #header>
                    <span>
                      课堂表现
                      <el-tooltip
                        class="item"
                        effect="dark"
                        :content="content"
                        placement="top"
                      >
                        <i style="cursor: pointer" class="el-icon-info"></i>
                        <div slot="content">
                          排课时自定义初始分，并在授课过程中进行分数加减（取0～100分计算得分）
                        </div>
                      </el-tooltip>
                    </span>
                  </template>
                  <template slot-scope="scope">
                    <div
                      v-if="
                        ($route.query.type == 'add' ||
                          $route.query.type == 'edit') &&
                        showTotalEdit
                      "
                    >
                      <el-input
                        v-model="scope.row.usualScorePercentage"
                        oninput="value=value.replace(/[^\d.]/,'').replace(/(\.\d\d)\d+$/,'\$1'); if(parseFloat(value) > 100) value='100';"
                        style="width: 72px"
                      ></el-input>
                      %
                    </div>
                    <div v-else>
                      {{
                        scope.row.usualScorePercentage
                          ? scope.row.usualScorePercentage
                          : '0'
                      }}%
                    </div>
                  </template>
                </el-table-column>
                <el-table-column
                  align="center"
                  prop="homeworkScorePercentage"
                  label="课后作业"
                >
                  <template #header>
                    <span>
                      课后作业
                      <el-tooltip
                        class="item"
                        effect="dark"
                        :content="content"
                        placement="top"
                      >
                        <i style="cursor: pointer" class="el-icon-info"></i>
                        <div slot="content">
                          在授课过程中进行打分（满分100，取平均分计算得分）
                        </div>
                      </el-tooltip>
                    </span>
                  </template>
                  <template slot-scope="scope">
                    <div
                      v-if="
                        ($route.query.type == 'add' ||
                          $route.query.type == 'edit') &&
                        showTotalEdit
                      "
                    >
                      <el-input
                        v-model="scope.row.homeworkScorePercentage"
                        oninput="value=value.replace(/[^\d.]/,'').replace(/(\.\d\d)\d+$/,'\$1'); if(parseFloat(value) > 100) value='100';"
                        style="width: 72px"
                      ></el-input>
                      %
                    </div>
                    <div v-else>
                      {{
                        scope.row.homeworkScorePercentage
                          ? scope.row.homeworkScorePercentage
                          : '0'
                      }}%
                    </div>
                  </template>
                </el-table-column>
                <el-table-column
                  align="center"
                  prop="processExamScoreTotal"
                  label="任务考核"
                >
                  <template #header>
                    <span>
                      任务考核
                      <el-tooltip
                        class="item"
                        effect="dark"
                        :content="content"
                        placement="top"
                      >
                        <i style="cursor: pointer" class="el-icon-info"></i>
                        <div slot="content">
                          编辑课程时在内容中创建，学生学习该内容时进行考核，按照【任务考核权重明细】计算得分
                        </div>
                      </el-tooltip>
                    </span>
                  </template>
                  <template slot-scope="scope">
                    <div
                      v-if="
                        ($route.query.type == 'add' ||
                          $route.query.type == 'edit') &&
                        showTotalEdit
                      "
                    >
                      <el-input
                        v-model="scope.row.processScorePercentage"
                        oninput="value=value.replace(/[^\d.]/,'').replace(/(\.\d\d)\d+$/,'\$1'); if(parseFloat(value) > 100) value='100';"
                        style="width: 72px"
                      ></el-input>
                      %
                    </div>
                    <div v-else>
                      {{
                        scope.row.processScorePercentage
                          ? scope.row.processScorePercentage
                          : '0'
                      }}%
                    </div>
                  </template>
                </el-table-column>
              </el-table-column>
              <el-table-column
                align="center"
                prop="examScorePercentage"
                label="终结性考核"
              >
                <template #header>
                  <span>
                    终结性考核
                    <el-tooltip
                      class="item"
                      effect="dark"
                      :content="content"
                      placement="top"
                    >
                      <i style="cursor: pointer" class="el-icon-info"></i>
                      <div slot="content">
                        编辑课程时在期末考核中创建，学生期末考核中进行考核，按照【终结性考核权重明细】计算得分
                      </div>
                    </el-tooltip>
                  </span>
                </template>
                <template slot-scope="scope">
                  <div
                    v-if="
                      ($route.query.type == 'add' ||
                        $route.query.type == 'edit') &&
                      showTotalEdit
                    "
                  >
                    <el-input
                      v-model="scope.row.examScorePercentage"
                      oninput="value=value.replace(/[^\d.]/,'').replace(/(\.\d\d)\d+$/,'\$1'); if(parseFloat(value) > 100) value='100';"
                      style="width: 72px"
                    ></el-input>
                    %
                  </div>
                  <div v-else>
                    {{
                      scope.row.examScorePercentage
                        ? scope.row.examScorePercentage
                        : '0'
                    }}%
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <!-- 配分明细操作行 -->
          <div class="score_detail_title">
            <div class="flex">
              配分明细
              <span class="score_detail_title_tip"
              >注：每项配分至100%，算分时系统根据总评自动折算</span
              >
            </div>
            <div class="flex">
              <!-- 勾选列 -->
              <!-- 2.1.2 通用课程勾选项 -->
              <div class="checkboxs">
                <el-checkbox
                  v-for="(item, index) in checkedList"
                  :key="index"
                  @change="changeCheckBox"
                  :disabled="
                    !showEdit &&
                    ($route.query.type == 'add' ||
                      $route.query.type == 'edit' ||
                      $route.query.type == 'detail' ||
                      type == 'detail')
                  "
                  v-model="item.checked"
                >{{ item.checkName }}
                </el-checkbox>
              </div>
              <!-- 备注标签 -->

              <el-tooltip class="item" effect="dark" placement="top-start">
                <i class="el-icon-info" style="margin: 4px 8px 0 16px"></i>
                <div slot="content">
                  <div v-if="!courseType == 3">
                    未勾选&新增作业/考核内容：新增的考核内容占比默认为0%；<br/>
                    未勾选&删除作业/考核内容：根据当前比例重新分配占比。<br/>
                  </div>
                  <div v-else>
                    未勾选&新增作业/考核内容：新增的考核内容占比默认为0%；<br/>
                    未勾选&删除作业/考核内容：根据当前比例重新分配占比。<br/>
                  </div>
                </div>
              </el-tooltip>

              <div>
                <el-button
                  size="mini"
                  @click="showEdit = true"
                  v-show="
                    !showEdit &&
                    ($route.query.type == 'add' || $route.query.type == 'edit')
                  "
                >编 辑
                </el-button>
                <el-button
                  size="mini"
                  v-show="showEdit"
                  v-preventReClick
                  type="primary"
                  @click="checkSignAll"
                >保 存
                </el-button>
              </div>
            </div>
          </div>
          <!-- 配分明细表 -->
          <div class="daily_score_detail">
            <div
              class="flex_center daily_score_detail_item"
              v-for="(item, index) in checkedList"
              :key="index"
            >
              <div style="height: 100%">
                <div class="text">
                  <div>{{ item.name }}</div>
                </div>
              </div>
              <div
                style="width: 100%"
                v-if="item.key == 'homeworkCourseIndexScoreEntityList'"
              >
                <el-table
                  :data="data.homeworkCourseIndexScoreEntityList"
                  v-loading="loading"
                  border
                  style="width: 100%"
                >
                  <el-table-column
                    align="center"
                    prop="ancestorsName"
                    :label="item.tableLable"
                  >
                    <template slot-scope="scope">
                      <el-tooltip
                        effect="dark"
                        :content="scope.row.ancestorsName"
                        placement="top"
                        :open-delay="300"
                      >
                        <span style="cursor: pointer">{{
                            filterTxt(scope.row.ancestorsName)
                          }}</span>
                      </el-tooltip>
                    </template>
                  </el-table-column>
                  <el-table-column width="266" align="center" label="权重(%)">
                    <template slot-scope="scope">
                      <div
                        v-if="
                          ($route.query.type == 'add' ||
                            $route.query.type == 'edit') &&
                          showEdit
                        "
                      >
                        <el-input
                          v-model="scope.row.homeworkScorePercentage"
                          oninput="value=value.replace(/[^\d.]/,'').replace(/(\.\d\d)\d+$/,'\$1'); if(parseFloat(value) > 100) value='100';"
                          style="width: 72px"
                        ></el-input>
                        %
                      </div>
                      <div v-else>
                        {{
                          scope.row.homeworkScorePercentage
                            ? scope.row.homeworkScorePercentage
                            : '0'
                        }}%
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
                <div class="sumtext">合计：{{ sumHomework.toFixed(2) }}%</div>
              </div>
              <div
                style="width: 100%"
                v-if="item.key == 'processCourseIndexScoreEntityList'"
              >
                <el-table
                  :data="data.processCourseIndexScoreEntityList"
                  v-loading="loading"
                  border
                  style="width: 100%"
                >
                  <el-table-column
                    align="center"
                    prop="ancestorsName"
                    :label="item.tableLable"
                  >
                    <template slot-scope="scope">
                      <el-tooltip
                        effect="dark"
                        :content="scope.row.ancestorsName"
                        placement="top"
                        :open-delay="300"
                      >
                        <span style="cursor: pointer">{{
                            filterTxt(scope.row.ancestorsName)
                          }}</span>
                      </el-tooltip>
                    </template>
                  </el-table-column>
                  <el-table-column width="266" align="center" label="权重(%)">
                    <template slot-scope="scope">
                      <div
                        v-if="
                          ($route.query.type == 'add' ||
                            $route.query.type == 'edit') &&
                          showEdit
                        "
                      >
                        <el-input
                          v-model="scope.row.processScorePercentage"
                          oninput="value=value.replace(/[^\d.]/,'').replace(/(\.\d\d)\d+$/,'\$1'); if(parseFloat(value) > 100) value='100';"
                          style="width: 72px"
                        ></el-input>
                        %
                      </div>
                      <div v-else>
                        {{
                          scope.row.processScorePercentage
                            ? scope.row.processScorePercentage
                            : '0'
                        }}%
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
                <div class="sumtext">合计：{{ sumExam.toFixed(2) }}%</div>
              </div>
              <div
                style="width: 100%"
                v-if="item.key == 'ccCourseIndexScoreEntityList'"
              >
                <el-table
                  :data="data.ccCourseIndexScoreEntityList"
                  v-loading="loading"
                  border
                  style="width: 100%"
                >
                  <el-table-column
                    align="center"
                    prop="ancestorsName"
                    :label="item.tableLable"
                  >
                    <template slot-scope="scope">
                      <el-tooltip
                        effect="dark"
                        :content="scope.row.ancestorsName"
                        placement="top"
                        :open-delay="300"
                      >
                        <span style="cursor: pointer">{{
                            filterTxt(scope.row.ancestorsName)
                          }}</span>
                      </el-tooltip>
                    </template>
                  </el-table-column>
                  <el-table-column width="266" align="center" label="权重(%)">
                    <template slot-scope="scope">
                      <div
                        v-if="
                          ($route.query.type == 'add' ||
                            $route.query.type == 'edit') &&
                          showEdit
                        "
                      >
                        <el-input
                          v-model="scope.row.scorePercentage"
                          oninput="value=value.replace(/[^\d.]/,'').replace(/(\.\d\d)\d+$/,'\$1'); if(parseFloat(value) > 100) value='100';"
                          style="width: 72px"
                        ></el-input>
                        %
                      </div>
                      <div v-else>
                        {{
                          scope.row.scorePercentage
                            ? scope.row.scorePercentage
                            : '0'
                        }}%
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
                <div class="sumtext">合计：{{ sumFinish.toFixed(2) }}%</div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { updateGuide } from '@/api/login'
import { getDistributionList, submitDistribution } from '@/api/course/course'
import onboardingGuide from '@/components/onboardingGuide'

export default {
  name: 'scoreDialog',
  components: {
    onboardingGuide
  },
  props: {
    open: {
      type: Boolean,
      default: false
    },
    courseTemplate: {
      type: [String, Number]
    },
    courseType: {
      type: [String, Number]
    },
    courseId: {
      type: [String, Number],
      default: ''
    },
    type: {
      type: [String, Number],
      default: 'edit'
    }
  },
  watch: {
    'data.homeworkCourseIndexScoreEntityList': {
      handler(val) {
        console.log(val, 'homeworkCourseIndexScoreEntityList')
        if (val.length > 0) {
           // 初始值为 0
          this.sumHomework = val.reduce(
            (accumulator, currentHomework) => {
              // 确保 homeworkScorePercentage 是数字类型
              const score = parseFloat(currentHomework.homeworkScorePercentage)

              // 如果解析失败（NaN），跳过该项
              if (isNaN(score)) {
                console.warn(
                  'Invalid homeworkScorePercentage:',
                  currentHomework
                )
                return accumulator
              }

              // 累加有效分数
              return accumulator + score
            },
            0
          )
        }
      },
      deep: true
    },
    'data.processCourseIndexScoreEntityList': {
      handler(val) {
        console.log(val, 'homeworkCourseIndexScoreEntityList')
        if (val.length > 0) {
           // 初始值为 0
          this.sumExam = val.reduce(
            (accumulator, currentHomework) => {
              // 确保 processScorePercentage 是数字类型
              const score = parseFloat(currentHomework.processScorePercentage)

              // 如果解析失败（NaN），跳过该项
              if (isNaN(score)) {
                console.warn(
                  'Invalid processScorePercentage:',
                  currentHomework
                )
                return accumulator
              }

              // 累加有效分数
              return accumulator + score
            },
            0
          )
        }
      },
      deep: true
    },
    'data.ccCourseIndexScoreEntityList': {
      handler(val) {
        console.log(val, 'ccCourseIndexScoreEntityList')
        if (val.length > 0) {
           // 初始值为 0
          this.sumFinish = val.reduce(
            (accumulator, currentHomework) => {
              // 确保 scorePercentage 是数字类型
              const score = parseFloat(currentHomework.scorePercentage)

              // 如果解析失败（NaN），跳过该项
              if (isNaN(score)) {
                console.warn('Invalid scorePercentage:', currentHomework)
                return accumulator
              }

              // 累加有效分数
              return accumulator + score
            },
            0
          )
        }
      },
      deep: true
    },
    finishExamScore: {
      handler() {
        if (this.courseType == 3) {
          this.updateTotalExamScore()
        }
      },
      deep: true
    },
    processExamScore: {
      handler() {
        if (this.courseType == 3) {
          this.updateTotalExamScore()
        }
      },
      deep: true
    },
    examTypeList: {
      handler() {
        if (this.courseType == 3) {
          this.updateTotalExamScore()
        }
      },
      deep: true
    },
    distributionList: {
      handler() {
        this.dailyScoreList[0].scorePercentage = this.distributionList[0].dailyScoreTotal
        if (
          this.$route.query.type == 'add' ||
          this.$route.query.type == 'edit'
        ) {
          if (this.courseType == 3) {
            let dailyTotalScore = this.distributionList[0].dailyScoreTotal
            let homeworkScoreTotal =
              this.distributionList[0].homeworkScoreTotal
            let processTotalScore =
              this.distributionList[0].processExamScoreTotal
            let finishTotalScore =
              this.distributionList[0].finishExamScoreTotal
            this.examTypeList[0].scorePercentage = dailyTotalScore
            this.examTypeList[1].scorePercentage = homeworkScoreTotal
            this.distributeScores(this.processExamScore, processTotalScore)
            this.distributeScores(this.finishExamScore, finishTotalScore)
          } else {
            let dailyTotalScore = this.distributionList[0].dailyScoreTotal
            let processTotalScore =
              this.distributionList[0].processExamScoreTotal
            let finishTotalScore =
              this.distributionList[0].finishExamScoreTotal
            this.dailyScoreList[0].scorePercentage = dailyTotalScore
            this.distributeScores(this.processExamScore, processTotalScore)
            this.distributeScores(this.finishExamScore, finishTotalScore)
          }
        }
      },
      deep: true
    },

    open(val) {
      console.log(this.type, this.$store.getters.curRole)
      if (val) {
        this.getDistributionList()
        //是否开启新手指导
        if (
          (this.type == 'add' || this.type == 'edit') &&
          this.$store.getters.curRole == 'teacher'
        ) {
          if (
            this.$store.getters.guide == 0 ||
            this.$store.getters.guide == 1
          ) {
            this.onboardingGuideShow = true
            this.$nextTick(() => {
              console.log(this.$refs.studentScoreEdit)
              // 确保 myElement 存在
              if (this.$refs.studentScoreEdit) {
                const rect =
                  this.$refs.studentScoreEdit.getBoundingClientRect()

                this.onboardingGuideRect = {
                  top: rect.top + 20,
                  left: rect.left + 10
                }
                console.log('距离屏幕顶部:', this.onboardingGuideRect)
              } else {
                console.log('元素未找到')
              }
            })
          } else {
            this.onboardingGuideShow = false
          }
        }
      }
    }
  },
  data() {
    return {
      sumHomework: 0,
      sumExam: 0,
      sumFinish: 0,
      onboardingGuideShow: false,
      onboardingGuideRect: {
        top: 0,
        left: 0
      },
      content: '',
      data: {},
      checkedList: [],
      needAuto: false,
      showEdit: false,
      showTotalEdit: false,
      dailyScore: '',
      loading: false,
      distributionList: [
        {
          processExamScoreTotal: 0,
          finishExamScoreTotal: 0,
          homeworkScoreTotal: 0,
          dailyScoreTotal: 0
        }
      ],
      totalExamScore: [
        {
          name: '',
          totalScore: 0
        }
      ],
      processExamScore: [],
      finishExamScore: [],
      examScorePercentage: 0,
      processScorePercentage: 0,
      dailyScoreList: [
        {
          id: 0,
          name: '课堂表现分',
          scorePercentage: ''
        }
      ],
      examTypeList: [
        {
          id: 0,
          name: '课堂表现',
          scorePercentage: ''
        },
        {
          id: 1,
          name: '课后作业',
          scorePercentage: ''
        }
      ]
    }
  },
  methods: {
    async step5Click() {
      this.showTotalEdit = true
      try {
        // 1 为第一个新手引导 2为第二个新手引导 如果为0则是没有新手引导变1 如果触发过第1个新手引导再触发这个则为3
        let guide = this.$store.getters.guide == 0 ? 2 : 3
        let res = await updateGuide({
          guide: guide,
          userId: this.$store.getters.userId
        })
        if (res.code == 200) {
          this.$store.dispatch('Setguide', guide)
        }
      } catch (error) {
      }
    },
    filterTxt(input) {
      const fields = input.split('/')
      let txt = ''
      if (fields.length > 3) {
        const secondField = fields[1] // 第二个字段
        const lastField =
          fields[fields.length - 1].length > 10
            ? fields[fields.length - 1].substring(0, 10) + '...'
            : fields[fields.length - 1]

        // 如果第二个字段的长度大于10，则截短并在末尾添加省略号
        if (secondField.length > 10) {
          fields[1] = secondField.substring(0, 10) + '...'
          txt = `${fields[0]}/${fields[1]}/${lastField}`
        } else {
          txt = `${fields[0]}/${fields[1]}/.../${lastField}`
        }
      } else {
        txt =
          fields.length > 2
            ? `${fields[0]}/${fields[1]}/${fields[2]}`
            : `${fields[0]}/${fields[1]}`
      }

      return txt
    },
    updateTotalExamScore() {
      let total = 0
      let examScorePercentage = 0
      let processScorePercentage = 0
      for (const argument of this.finishExamScore) {
        total += parseFloat(
          argument.scorePercentage ? argument.scorePercentage : 0
        )
        examScorePercentage += parseFloat(
          argument.scorePercentage ? argument.scorePercentage : 0
        )
      }
      for (const argument of this.processExamScore) {
        total += parseFloat(
          argument.scorePercentage ? argument.scorePercentage : 0
        )
        processScorePercentage += parseFloat(
          argument.scorePercentage ? argument.scorePercentage : 0
        )
      }
      for (const argument of this.examTypeList) {
        total += parseFloat(
          argument.scorePercentage ? argument.scorePercentage : 0
        )
      }
      this.totalExamScore[0].totalScore = total
      this.examScorePercentage = examScorePercentage
      this.processScorePercentage = processScorePercentage
    },
    checkTotalAll() {
      const total = Object.values(this.distributionList[0]).reduce(
        (acc, val) => {
          if (val === '') {
            return acc // 如果是空字符串，直接返回当前累加值
          } else {
            return acc + parseFloat(val) // 否则将字符串转换为数字并累加
          }
        },
        0
      )
      if (total != 100) {
        this.$modal.msgWarning(
          `当前【总评】配比之和为${total}%,请合理分配比例，确保分配比例总和为100%`
        )
        return false
      }
      this.showTotalEdit = false
      this.confirm()
      return true
    },
    roundToInteger(num, epsilon = 1e-10) {
      if (Math.abs(Math.round(num) - num) < epsilon) {
        return Math.round(num)
      }
      return num
    },
    checkSignAll() {
      if (this.checkedList.length > 0) {
        let text = '当前'
        for (let k = 0; k < this.checkedList.length; k++) {
          if (this.checkedList[k].checked && this.data[this.checkedList[k].key].length > 0) {
            this.checkedList[k].sum = 0
            for (let i = 0; i < this.data[this.checkedList[k].key].length; i++) {
              if (this.checkedList[k].key == 'homeworkCourseIndexScoreEntityList') {
                this.checkedList[k].sum += Number(this.data[this.checkedList[k].key][i].homeworkScorePercentage - 0)
              } else if (this.checkedList[k].key == 'processCourseIndexScoreEntityList') {
                this.checkedList[k].sum += Number(this.data[this.checkedList[k].key][i].processScorePercentage - 0)
              } else {
                this.checkedList[k].sum += Number(this.data[this.checkedList[k].key][i].scorePercentage - 0)
              }
            }
            if (this.roundToInteger(this.checkedList[k].sum) > 100) {
              text += `${this.checkedList[k].name}总占比为${this.roundToInteger(this.checkedList[k].sum)}%,`
              text += '无法保存，请重新编辑。'
              this.$confirm(text, '提示', {
                showCancelButton: false,
                confirmButtonText: '关闭',
                type: 'warning'
              }).then(() => {
              })
              return
            }
            if (this.roundToInteger(this.checkedList[k].sum) != 100) {
              text += `${this.checkedList[k].name}总占比为${this.roundToInteger(this.checkedList[k].sum)}%,`
              text += '是否确认保存?'
              this.$confirm(text, '保存确认', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                this.showEdit = false
                this.confirm()
              })
              return
            }
          }
        }
        this.$confirm('是否确认保存', '保存确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.showEdit = false
          this.confirm()
        })
      } else {
        // 请先勾选提示
        this.$modal.msgWaring('请先勾选')
      }
    },
    //平均配分方法
    distributeScores(examScoreList, totalScore, key) {
      const processTotalNum = examScoreList.length
      const averageScore = (totalScore / processTotalNum).toFixed(2) // 计算平均分数并保留两位小数
      let remainingScore = (
        totalScore -
        averageScore * (processTotalNum - 1)
      ).toFixed(2) // 计算剩余的分数并保留两位小数

      examScoreList.forEach((item, index) => {
        if (index === processTotalNum - 1) {
          // 最后一个元素
          item[key] = parseFloat(remainingScore) // 将剩余分数转换为浮点数
        } else {
          item[key] = parseFloat(averageScore) // 将平均分数转换为浮点数
        }
        if (key == 'homeworkScorePercentage') {
          item.processScorePercentage = null
        } else {
          item.homeworkScorePercentage = null
        }
      })
      // 强制渲染
      this.$forceUpdate()
      console.log(examScoreList)
    },
    async confirm() {
      let params = JSON.parse(JSON.stringify(this.data))
      if (this.courseType == 3) {
        params.usualScorePercentage =
          this.distributionList[0].usualScorePercentage
        params.homeworkScorePercentage =
          this.distributionList[0].homeworkScorePercentage
        params.processScorePercentage =
          this.distributionList[0].processScorePercentage
        params.examScorePercentage =
          this.distributionList[0].examScorePercentage
      } else {
        params.attendanceScorePercentage =
          this.distributionList[0].attendanceScorePercentage
        params.disciplineScorePercentage =
          this.distributionList[0].disciplineScorePercentage
        params.usualScorePercentage =
          this.distributionList[0].usualScorePercentage
        params.homeworkScorePercentage =
          this.distributionList[0].homeworkScorePercentage
        params.processScorePercentage =
          this.distributionList[0].processScorePercentage
        params.otherScorePercentage =
          this.distributionList[0].otherScorePercentage
      }
      params.averageFlag =
        this.checkedList.length > 2 ? (this.checkedList[2].checked ? 1 : 0) : 0
      params.homeworkAvgFlag = this.checkedList[0].checked ? 1 : 0
      params.processAvgFlag = this.checkedList[1].checked ? 1 : 0
      params.homeworkCourseIndexScoreEntityList.map((item) => {
        delete item.processScorePercentage
        delete item.scorePercentage
      })
      params.processCourseIndexScoreEntityList.map((item) => {
        delete item.homeworkScorePercentage
        delete item.scorePercentage
      })
      params.ccCourseIndexScoreEntityList.map((item) => {
        delete item.homeworkScorePercentage
        delete item.processScorePercentage
      })
      let res = await submitDistribution(params)
      const { code } = res
      if (code == 200) {
        this.$modal.msgSuccess('保存成功')
      }
    },
    changeCheckBox() {
      this.$nextTick(() => {
        for (let i = 0; i < this.checkedList.length; i++) {
          if (this.checkedList[i].checked) {
            if (
              this.checkedList[i].key == 'homeworkCourseIndexScoreEntityList'
            ) {
              this.distributeScores(
                this.data[this.checkedList[i].key],
                100,
                'homeworkScorePercentage'
              )
            } else if (
              this.checkedList[i].key == 'processCourseIndexScoreEntityList'
            ) {
              this.distributeScores(
                this.data[this.checkedList[i].key],
                100,
                'processScorePercentage'
              )
            } else {
              this.distributeScores(
                this.data[this.checkedList[i].key],
                100,
                'scorePercentage'
              )
            }
          }
        }
      })

      console.log(this.data)
      // this.confirm();
    },
    async getDistributionList() {
      this.loading = true
      try {
        let res = await getDistributionList(this.courseId)
        const { code, data } = res
        this.data = JSON.parse(JSON.stringify(data))

        if (code == 200) {
          //工学一体课程，表结构不一样
          if (this.courseType == 3) {
            this.distributionList = [
              {
                usualScorePercentage: data.usualScorePercentage
                  ? data.usualScorePercentage
                  : 0,
                homeworkScorePercentage: data.homeworkScorePercentage
                  ? data.homeworkScorePercentage
                  : 0,
                processScorePercentage: data.processScorePercentage
                  ? data.processScorePercentage
                  : 0,
                examScorePercentage: data.examScorePercentage
                  ? data.examScorePercentage
                  : 0
              }
            ]
            this.checkedList = [
              {
                key: 'homeworkCourseIndexScoreEntityList',
                checked: data.homeworkAvgFlag == 1,
                name: '课后作业',
                checkName: '课后作业平均分',
                tableLable: '作业位置',
                sum: 0
              },
              {
                key: 'processCourseIndexScoreEntityList',
                checked: data.processAvgFlag == 1,
                name: '任务考核',
                checkName: '任务考核平均分',
                tableLable: '考核位置',
                sum: 0
              },
              {
                key: 'ccCourseIndexScoreEntityList',
                checked: data.averageFlag == 1,
                tableLable: '考核位置',
                sum: 0,
                name: '终结性考核',
                checkName: '终结性考核平均分'
              }
            ]
          } else {
            this.checkedList = [
              {
                key: 'homeworkCourseIndexScoreEntityList',
                checked: data.homeworkAvgFlag == 1,
                name: '课后作业',
                checkName: '课后作业平均分',
                tableLable: '作业位置',
                sum: 0
              },
              {
                key: 'processCourseIndexScoreEntityList',
                checked: data.processAvgFlag == 1,
                name: '课后考核',
                checkName: '课后考核平均分',
                tableLable: '考核位置',
                sum: 0
              }
            ]
            this.distributionList = [
              {
                attendanceScorePercentage: data.attendanceScorePercentage
                  ? data.attendanceScorePercentage
                  : 0,
                disciplineScorePercentage: data.disciplineScorePercentage
                  ? data.disciplineScorePercentage
                  : 0,
                usualScorePercentage: data.usualScorePercentage
                  ? data.usualScorePercentage
                  : 0,
                homeworkScorePercentage: data.homeworkScorePercentage
                  ? data.homeworkScorePercentage
                  : 0,
                processScorePercentage: data.processScorePercentage
                  ? data.processScorePercentage
                  : 0,
                otherScorePercentage: data.otherScorePercentage
                  ? data.otherScorePercentage
                  : 0,
                examScorePercentage: data.examScorePercentage
                  ? data.examScorePercentage
                  : 0
              }
            ]
          }
          console.log(this.courseType, this.distributionList)
        }
      } catch (e) {
        console.error(e)
      } finally {
        this.loading = false
      }
    },
    cancel() {
      this.showEdit = false
      this.showTotalEdit = false
      this.distributionList = [
        {
          processExamScoreTotal: 0,
          finishExamScoreTotal: 0,
          homeworkScoreTotal: 0,
          dailyScoreTotal: 0
        }
      ]
      this.dailyScoreList = [
        {
          id: 0,
          name: '课堂表现分',
          scorePercentage: ''
        }
      ]
      this.examTypeList = [
        {
          id: 0,
          name: '课堂表现',
          scorePercentage: ''
        },
        {
          id: 1,
          name: '课后作业',
          scorePercentage: ''
        }
      ]
      this.processExamScore = []
      this.finishExamScore = []
      this.$emit('update:open', false)
    }
  }
}
</script>

<style scoped lang="scss">
// ::v-deep .el-dialog {
//   .el-dialog__body {
//     max-height: calc(100vh - 300px) !important;
//     overflow-y: auto;
//     overflow-x: hidden
//   }
// }
.daily_score {
  width: 100%;
  display: flex;
  flex-direction: column;
  margin-bottom: 10px;

  .title {
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 10px;

    .el-icon-edit {
      font-size: 16px;
      cursor: pointer;
      color: #1ab394;
    }
  }
}

.score_detail_title {
  .score_detail_title_tip {
    line-height: 26px;
    margin-left: 8px;
    font-family: PingFangSC, PingFang SC, sans-serif;
    font-weight: 400;
    font-size: 16px;
    color: #f7b500;
  }

  .checkboxs {
    margin-top: 2px;
  }

  font-size: 18px;
  font-weight: bold;
  margin-top: 35px;
  margin-bottom: 10px;
  display: flex;
  justify-content: space-between;

  .el-icon-edit,
  .el-icon-success {
    font-size: 16px;
    cursor: pointer;
    color: #1ab394;
  }

  .el-icon-question {
    font-size: 14px;
    cursor: pointer;
    margin-left: 4px;
  }
}

.daily_score_detail {
  .daily_score_detail_item {
    margin-bottom: 10px;
  }

  .sumtext {
    border: 1px solid #e8eaeb;
    border-top: 0;
    text-align: center;
    background: #fafafa;
    height: 44px;
    line-height: 44px;
  }

  width: 100%;
  display: flex;
  flex-direction: column;
  margin-bottom: 10px;
  height: calc(100vh - 315px);
  overflow-y: scroll;
  overflow-x: hidden;

  .flex_center {
    display: flex;
    align-items: center;

    .text {
      width: 120px;
      height: 100%;
      background: #fafafa;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      border: 1px solid #e8eaeb;
      border-right: 0;
    }

    .text_top {
      width: 120px;
      height: 44px;
      background: #fafafa;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      border: 1px solid #dfe6ec;
      border-right: 0;
      border-bottom: 0;
    }
  }
}

.containBox {
  height: calc(100vh - 260px);
  overflow-y: auto;
  overflow-x: hidden;
}

.sign {
  width: 1120px;
  height: 40px;
  background: #fef1e1;
  color: #716d69;
  font-weight: 500;
  font-size: 14px;
  display: flex;
  align-items: center;
  margin: -20px 0 20px -40px;

  .el-icon-info {
    color: #f89a34;
    margin: 0 16px 0 24px;
  }
}

::v-deep .el-dialog .el-dialog__body {
  padding: 20px 40px 20px 40px !important;
}
</style>
